/*jl3PIwMb5MyMAa5yfSj+PA9VwPPCtx9RYVJuQHFYJAQ=*/
import { ajax,toast } from 'nc-lightapp-front';
import  { headButton,bodyButton,innerButton} from './pubUtils/buttonName';
import { refreshChildVO2HeadVO } from './pubUtils/billPubUtil.js';
let ruleField = 'allocobjrule';//对象分摊规则字段编码
//联查期间分摊
function allocperiodruleLinkQuery(that){
    //判断是行否存在期间分摊规则
    let allData = that.props.cardTable.getAllRows(that.tableId);
    let pk_items=[];
    let pk_billtype = null;
    if(allData&&allData.length>0){
        pk_billtype = that.props.form.getFormItemsValue(that.formId, 'pk_billtype').value;
        let pkField = getPKField(pk_billtype,"body");
        if(pkField){
            for(let i=0;i<allData.length;i++){
                let pk_periodrule = allData[i].values.pk_periodrule.value;
                let pk_item = allData[i].values[pkField].value;
                if(pk_periodrule&&pk_item){
                    pk_items.push(pk_item);
                }
            }
        }
    }
    if(pk_items&&pk_items.length>0){//有期间分摊规则，则跳转到对应分摊节点
        let url = '/nccloud/resources/arap/arapallocation/allocation/list/index.html'
        let info = getAllocationInfo(pk_billtype);//获取分摊处理应用编码和页面编码
        if(url&&info&&pk_items.length>0){
            that.props.openTo(url, {
                scene:'link_allocation',
                pk: pk_items,
                pagecode: info[1],
                appcode: info[0],
                backflag: 'noback'
            });
        }else{
            toast({ color: 'danger', content: that.state.json['public-000264'] }); /* 国际化处理： 当前单据表体行无期间分摊规则，无法进行联查*/
        }
    }else{
        toast({ color: 'danger', content: that.state.json['public-000264'] }); /* 国际化处理： 当前单据表体行无期间分摊规则，无法进行联查*/
    }
}

//点击分摊：弹出对话框
function showAllocation(that){
    const { modal } = that.props;
    let { show } = modal;
    that.props.form.setFormStatus(ruleField, "edit")
    let selectedData = that.props.cardTable.getCheckedRows(that.tableId);
    if(!selectedData||selectedData.length==0){
        toast({ color: 'danger', content: that.state.json['public-000265'] });/* 国际化处理： 请选择需要分摊的行!*/
        return;
    }
    show(ruleField)
}

//对象分摊确认执行：
function beSureAllocation() {
    let that = this;
    let  pk_allocobjrule = that.props.form.getFormItemsValue(ruleField, ruleField)?that.props.form.getFormItemsValue("allocobjrule", 'allocobjrule').value:null
    if(!pk_allocobjrule){
        let result = that.props.validatePageToToast([
            {
                name: ruleField,
                type: "form",
            }
        ]);
        if (result && !result.allPassed) {
            const { modal } = that.props;
            let { show } = modal;
            show(ruleField)
            that.props.form.setFormItemAutoFocus(ruleField, ruleField);//获取焦点
            return;
        }
    }

    //执行分摊
    let cardData = that.props.createMasterChildData(that.getPagecode(), that.formId, that.tableId);
    let selectedData = that.props.cardTable.getCheckedRows(that.tableId);
    let indexs = [];
    if(!selectedData||selectedData.length==0){
        toast({ color: 'danger', content: that.state.json['public-000265'] });/* 国际化处理： 请选择需要分摊的行!*/
        return;
    }else{
        for(let i=0;i<selectedData.length;i++){
            indexs.push(selectedData[i].index.toString());
        }
    }
    cardData = fileRows(that,cardData);
    ajax({
        url: '/nccloud/arap/arappub/arapbillexectallocation.do',
        data: {
            pk_org: that.props.form.getFormItemsValue(that.formId, 'pk_org').value,
            cardData: cardData,
            pk_allocobjrule: pk_allocobjrule,
            pageId: that.getPagecode(),
            billType: that.billType,
            pk_items:indexs
        },
        async: false,
        success: (res) => {
            let { success, data } = res;
            if (success) {
                // if (data&&data.head) {
                // 	that.props.form.setAllFormValue({ [that.formId]: res.data.head[that.formId] });
                // }
                if (data&&data.body) {
                    that.props.cardTable.setTableData(that.tableId, res.data.body[that.tableId]);
                }
                let selectedData = that.props.cardTable.getCheckedRows(that.tableId);
                if(selectedData&&selectedData.length>0){
                    that.props.button.setButtonDisabled(['DelLine','Allocate'], false);
                }else{
                    that.props.button.setButtonDisabled(['DelLine','Allocate'], true);
                }
                refreshChildVO2HeadVO(that.props, that.formId, that.tableId);
                //清空规则字段值
                that.props.form.setFormItemsValue(ruleField,  { ruleField: { value: '', display: '' } })
                toast({ color: 'success', content: that.state.json['public-000266']  });/*国际化处理：分摊成功！ */
            }
        }
    });

}

//去掉刪除行
function fileRows(that,cardData){
    let bodys = cardData.body[that.tableId].rows;
    let length = bodys.length;
    let retbody = [];
    for (let i = 0; i < length; i++) {
        let body = bodys[i];
        if (!(body && body.status && body.status == '3')) {
            retbody.push(body);
        } 
    }
    cardData.body[that.tableId].rows =retbody;
    return cardData;
}


//分摊取消事件
function  cancelAllocation(that){
    that.props.modal.close(ruleField);
    that.props.form.setFormItemsValue(ruleField,  { ruleField: { value: '', display: '' } })
}

//设置单据分摊字段相关属性
function setAllocField(that){
    let meta = that.props.meta.getMeta();
    let pk_periodrule = that.props.form.getFormItemsValue(that.formId, 'pk_periodrule').value;
    meta[that.formId].items.map((item,index)=>{
        if(item.attrcode=='startdate'||item.attrcode=='enddate'||item.attrcode=='firstallocdate'){
            if(pk_periodrule){
                item.required = true;
            }else{
                item.required = false;
            }
        }
        return item;
	});

    that.props.meta.setMeta(meta);
}

//控制联查期间分摊按钮显示
function ctrAllocBtn(that){
    //当存在期间分摊且单据生效时按钮显示
    //let pk_periodrule = that.props.form.getFormItemsValue(that.formId, 'pk_periodrule').value;
    let effectstatus = that.props.form.getFormItemsValue(that.formId, 'effectstatus').value;
    let isinit = that.props.form.getFormItemsValue(that.formId, 'isinit').value;
    let status = that.props.getUrlParam('status');
    if(effectstatus&&effectstatus==10&&status=='browse'){
        that.props.button.setButtonVisible([headButton.AllocperiodruleLinkQuery], true);
    }else{
        that.props.button.setButtonVisible([headButton.AllocperiodruleLinkQuery], false);
    }
    //浏览态非自由态非审批中心的单据：隐藏修改按钮
    let approvestatus = that.props.form.getFormItemsValue(that.formId, 'approvestatus').value;
    let pk_org_v = that.props.form.getFormItemsValue(that.formId, 'pk_org_v').value;
    let scene = that.props.getUrlParam('scene');
    if(status == 'browse'&&scene != 'approve' && scene != 'approvesce'){
        if(isinit||isinit=="Y"){
            that.props.button.setButtonVisible([headButton.Edit], true);
        }else if(approvestatus!=-1||(effectstatus&&effectstatus==10)){
            that.props.button.setButtonVisible([headButton.Edit], false);
        }else{
            if(pk_org_v){
                that.props.button.setButtonVisible([headButton.Edit], true);
            }else{
                that.props.button.setButtonVisible([headButton.Edit], false);
            }
        }
    }
    if(scene == 'approve' || scene == 'approvesce'){
        that.props.button.setButtonVisible([bodyButton.Allocate], false);
    }
    //我的审核场景的单据，如果单据没有生效，则显示修改按钮
    if (that.props.getUrlParam('scene') && that.props.getUrlParam('scene') == 'zycl'&&10!=effectstatus) {
        if(status=='browse'){
            that.props.button.setButtonVisible([headButton.Edit], true);
        }else{
            that.props.button.setButtonVisible([headButton.Edit], false);
        }
    }
}

//处理审批中心行按钮显示
function  dealBtnVisibleForApprovalCenter(that){
    let scene = that.props.getUrlParam('scene');
    let status = that.props.getUrlParam('status');
    let effectstatus = that.props.form.getFormItemsValue(that.formId, 'effectstatus').value;
    if (scene == 'approve' || scene == 'approvesce') {
        that.props.button.setButtonVisible([bodyButton.CopyLine, bodyButton.DelLine, bodyButton.AddLine, innerButton.Delete_inner,
            innerButton.Copy_inner, innerButton.Insert_inner,bodyButton.Allocate], false);
    }
    //来自流程中心的
    if (that.props.getUrlParam('mark') && that.props.getUrlParam('mark') == 'processCenter') {
        that.props.button.setButtonVisible([bodyButton.CopyLine, bodyButton.DelLine, bodyButton.AddLine, innerButton.Delete_inner,
            innerButton.Copy_inner, innerButton.Insert_inner,bodyButton.Allocate], false);
	}
    if (that.props.getUrlParam('scene') && that.props.getUrlParam('scene') == 'zycl') {
        //我的稽核场景 
        that.props.button.setButtonVisible([bodyButton.CopyLine, bodyButton.DelLine, bodyButton.AddLine, innerButton.Delete_inner,
            innerButton.Copy_inner, innerButton.Insert_inner,bodyButton.Allocate], false);
    }
    //我的审核场景的单据，如果单据没有生效，则显示修改按钮
    if (that.props.getUrlParam('scene') && that.props.getUrlParam('scene') == 'zycl'&&10!=effectstatus) {
        if(status=='browse'){
            that.props.button.setButtonVisible([headButton.Edit], true);
        }else{
            that.props.button.setButtonVisible([headButton.Edit], false);
        }
    }
}
    


//列表联查期间分摊规则
function ListAllocperiodruleLinkQuery(that){
    let checkedObj = getFirstCheckedData (that,that.tableId) 
    if(checkedObj&&checkedObj.data.values&&checkedObj.data.values['effectstatus']){
        //判断第一行是否有期间分摊规则：若无，则提示
        let effectstatus = checkedObj.data.values['effectstatus'].value;
        if(effectstatus!=10){
            toast({ color: 'danger', content: that.state.json['public-000268']});/**单据未生效无法联查 */
            return;
        }
        let pk_periodrule = checkedObj.data.values['pk_periodrule'].value;
        if(!pk_periodrule){//期间分摊规则为空
            toast({ color: 'danger', content: that.state.json['public-000264']}); /* 国际化处理： 当前单据无期间分摊规则，无法进行联查*/
            return;
        }
        let pk_billtype = checkedObj.data.values['pk_billtype'].value;
        let  pkField = getPKField(pk_billtype,"head");
        //跳转
        let pk_bill = checkedObj.data.values[pkField].value;
        let pk_bills = [];
        if(pk_bill){
            pk_bills = [pk_bill];
        }
        //跳转到分摊处理节点界面
        let url = '/nccloud/resources/arap/arapallocation/allocation/list/index.html'
        let allInfo = getAllocationInfo(pk_billtype);//获取分摊处理应用编码和页面编码
        if(url&&allInfo&&pk_bills.length>0){
            that.props.openTo(url, {
                scene:'link_allocation',
                pk: pk_bills,
                pagecode: allInfo[1],
                appcode: allInfo[0],
                backflag: 'noback'
            });
        }else{
            toast({ color: 'danger', content: that.state.json['public-000264'] }); /* 国际化处理： 当前单据表体行无期间分摊规则，无法进行联查*/
        }   
    }else{
        //请选中一行数据!
        toast({ color: 'danger', content: that.state.json['public-000267'] });
    }
}

//获取选中数据的第一行,选中多行的时候只取第一行数据
function getFirstCheckedData (that,tableId) {
	let checkedData = that.props.table.getCheckedRows(tableId,false);
	let checkedObj = null;
	if (checkedData.length > 0) {
		checkedObj = checkedData[0];
	}
	return checkedObj;
};

//获取单据对应的主键字段
function getPKField(pk_billtype,moduleId){
    let pkField=null;
    if(moduleId=='head'){
        if(pk_billtype=="F0"){
            pkField = 'pk_recbill';
        }else if(pk_billtype=="F1"){
            pkField = 'pk_payablebill';
        }else if(pk_billtype=="F2"){
            pkField = 'pk_gatherbill' ;
        }else if(pk_billtype=="F3"){
            pkField = 'pk_paybill' ;
        }
    }else {
        if(pk_billtype=="F0"){
            pkField = 'pk_recitem';
        }else if(pk_billtype=="F1"){
            pkField = 'pk_payableitem';
        }else if(pk_billtype=="F2"){
            pkField = 'pk_gatheritem' ;
        }else if(pk_billtype=="F3"){
            pkField = 'pk_payitem' ;
        }
    }
    return pkField;
}

//获取分摊处理页面信息
function getAllocationInfo(pk_billtype){
    let info=[];
    let pagecode = '20060ALLOC_allocation';
    let appcode = '20060ALLOC';
    if(pk_billtype){
        if(pk_billtype=="F1"||pk_billtype=="F3"){
            pagecode = '20080ALLOC_allocation';
            appcode = '20080ALLOC';
        }
    }
    info.push(appcode);
    info.push(pagecode);
    return info;
}

export {allocperiodruleLinkQuery,showAllocation,cancelAllocation,beSureAllocation,setAllocField,ctrAllocBtn,ListAllocperiodruleLinkQuery,dealBtnVisibleForApprovalCenter};
/*jl3PIwMb5MyMAa5yfSj+PA9VwPPCtx9RYVJuQHFYJAQ=*/